package com.example.alioss.controller;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSONObject;
import com.example.alioss.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码功能
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/html")
    public String captchaView(Map<String, Object> map) {
        return "captchaPage";
    }

    @RequestMapping("/captchaImage")
    public void createCaptcha(String type, String code, HttpServletResponse response) throws IOException {
        AbstractCaptcha captcha = null;
        if (StringUtils.isEmpty(type) || type.equals("line")) {
            captcha = CaptchaUtil.createLineCaptcha(200, 100);
        } else if (type.equals("gif")) {
            captcha = CaptchaUtil.createGifCaptcha(200, 100);
        } else if (type.equals("Shear")) {
            captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        } else if (type.equals("circle")) {
            captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 30);
        }
        if (!StringUtils.isEmpty(code)) {
            String captchaCode = captcha.getCode();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("verifyCode", captchaCode);
            RedisUtils.setValue(redisTemplate, "frontCode:" + code, jsonObject, 20);
        }
        // 图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }

    @ResponseBody
    @CrossOrigin
    @GetMapping("/verifyCaptcha")
    public Object verifyCaptchaCode(String code, String captcha) {
        JSONObject captchaCode = (JSONObject) RedisUtils.getValue(redisTemplate, "frontCode:" + code);
        System.out.println("captchaCode=" + captchaCode);
        if (captchaCode == null) return new Result(1, "验证码已过期！", false);
        if (captchaCode != null && captchaCode.getString("verifyCode").equals(captcha))
            return new Result(0, "验证码正确！", true);
        return new Result(1, "验证码错误！", false);
    }
}
